/*
 * XQUtil.java
 */

package xq.ide;

import java.net.URI;
import java.util.ServiceLoader;
import xq.api.XQException;
import xq.api.XQRequest;
import xq.api.XQResponse;
import xq.api.XQService;
import xq.api.XQServiceFactory;

/**
 *
 * @author ThorntonRP
 */
public class XQUtil {

	public static XQResponse<String> executeQuery(ConnectionInfo connInfo, XQRequest request) throws XQException {
		URI connectionURI = connInfo.getConnectionURI();
		ServiceLoader<XQServiceFactory> loader = ServiceLoader.load(XQServiceFactory.class);
		XQService xqueryService = null;
		for (XQServiceFactory factory : loader) {
			if (factory.acceptsURI(connectionURI)) {
				xqueryService = factory.create(connectionURI);
			}
		}
		if (xqueryService == null) {
			throw new XQException("No service available for URI \"" + connectionURI + "\"");
		} else {
			return xqueryService.queryToString(request);
		}
	}
	
	public static String format(String xml) {
		xml = xml.replace("><", ">\n<");
		String[] lines = xml.split("\n");
		int level = 0;
		String indent = "  ";
		StringBuilder sb = new StringBuilder(xml.length());
		for (String line : lines) {
			if (line.matches("^\\s*<[^/][^>]*?[^/]>\\s*$")) { // opening tag
				appendLine(sb, line.trim(), indent, level);
				level++;
			} else if (line.matches("^\\s*</[^>]*?>\\s*$")) { // closing tag
				level--;
				appendLine(sb, line.trim(), indent, level);
			} else {
				appendLine(sb, line.trim(), indent, level);
			}
		}
		return sb.toString();
	}

	private static void appendLine(StringBuilder sb, String line, String indent, int level) {
		for (int i = 0; i < level; i++) {
			sb.append(indent);
		}
		sb.append(line).append("\n");
	}

	private XQUtil() {
	}
}
